// subpage/pages/search/search.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchvalue:'',
    searchData:[],
    historyData:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      historyData:wx.getStorageSync('histoy') || []
    })
  },
  searchHandle(e){
    this.setData({
      searchvalue:e.detail
    })
    // 为空判断
    if(!e.detail){
      this.setData({
        searchData:[]
      })
      return
    }
    this.getData()

    let arr=wx.getStorageSync('histoy') || []

    let index=arr.findIndex(item=>{
      return item==e.detail
    })
    // 判重
      if(index==-1){
        // 历史记录添加不能超过10条
      if(arr.lenth>=10){
        arr.shift()
      }
        arr.push(e.detail)
        wx.setStorageSync('histoy', arr)

        this.setData({
          historyData:wx.getStorageSync('histoy') || []
        })
      }
  },

  //搜索接口
  getData(){
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
      data:{
        query:this.data.searchvalue
      },
      success:res=>{
        console.log(res);
        this.setData({
          searchData:res.data.message.goods
        })
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },
  // 跳转到商品详情页
  toInfo(e){
    wx.navigateTo({
      url: '/subpage/pages/goodsinfo/goodsinfo?id='+e.currentTarget.dataset.id,
    })
    // console.log(e);
  },
    // 历史记录的点击事件
  history(e){
    console.log(e.currentTarget.dataset.item);
    this.setData({
    searchvalue:e.currentTarget.dataset.item
    })
  },
    
  // 删除事件
  deletHanlde(){
   wx.removeStorageSync('histoy')
   this.setData({
    historyData:wx.getStorageSync('histoy') || []
  })
  }
})